package general;

/**
 * Title:        BaseBean
 * Description:  weaver sales for mrp (order , inventory , sales)
 * Copyright:    Copyright (c) 1995
 * Company:      weaver
 * @author liuyu
 * @version 1.0
 */

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weaver.conn.RecordSet;
import weaver.file.Prop;
import checkDetail.CheckBase;

public class BaseBean {

  private static Prop prop = Prop.getInstance() ;
  protected RecordSet recordSet;

  ClassLoader classloader = Thread.currentThread().getContextClassLoader();

   /** 成功 */
   public static String resultOk = "0";
   /** 部分需要修复 */
   public static String resultNeedFix = "1";
   /** 全部需要修复 */
   public static String resultNeedFixAll = "2";
   /** 失败 */
   public static String resultERROR = "3"; 
   
   /** 检测结果区域的DIV是否需要重新加载 */
   public String needReload;
  public String getPropValue(String fname , String key)  {
    return prop.getPropValue(fname , key) ;
  }


  public Properties LoadTemplateProp(String fname)  {
      return prop.loadTemplateProp(fname) ;
  }


  public void writeLog(Object obj) {
    writeLog(getClass().getName(),obj);
  }

  public void writeLog(String classname , Object obj)  {
      Log log= LogFactory.getLog(classname);
      if(obj instanceof Exception)
      log.error(classname ,(Exception)obj);
      else{
      log.error(obj);
      }
  }
  /**
   * 获取RecordSet
   * @return
   */
  public RecordSet getRecordSet(){
      try {
          recordSet = (RecordSet)Class.forName("weaver.conn.RecordSet").newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return recordSet;
  }
  /**
   * 获取RecordSet
   * @return
   */
  public void setRecordSet(){
      try {
          recordSet = (RecordSet)Class.forName("weaver.conn.RecordSet").newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
  
  //拼接详细信息(不带ID)
  protected String formatMessage(String name,String desc){
      return formatMessage(name, desc, null);
  }
  //拼接详细信息(带ID)
  protected String formatMessage(String name,String desc,String id){
      String message = "【" + name;
      if(id != null && !id.equals("")){
          message += "(" + id + ")";
      }
      message += "】";
      message += desc;
      return message;
  }
  //检测返回字符串
  public JSONObject formatReturnJsonCheck(String result,List retList,CheckBase checkBase){
      String msg = getMsgFromResult(1,result,checkBase.getClassName());
      return formatReturnJson(result, msg, retList,checkBase);
  }
  //修复返回字符串
  public JSONObject formatReturnJsonFix(String result,List retList,CheckBase checkBase){
      String msg = getMsgFromResult(2,result,checkBase.getClassName());
      return formatReturnJson(result, msg, retList,checkBase);
  }
  /**
   * 根据返回值拼接提示信息
   * @param checkOrFix 检测或修复
   * @param result 返回值
   * @param classinfo 文件描述
   * @return
   */
  private String getMsgFromResult(int checkOrFix,String result,String classinfo){
      String msg = classinfo;
      if(checkOrFix == 1){
          msg += "";
          if(resultOk.equals(result)){
              msg += "不需要修复。";
          }else if(resultNeedFix.equals(result)){
              msg += "部分需要修复。";
          }else if(resultNeedFixAll.equals(result)){
              msg += "需要修复。";
          }else if(resultERROR.equals(result)){
              msg += "检测失败。";
          }
      }else{
          msg += "修复";
          if(resultOk.equals(result)){
              msg += "成功。";
          }else if(resultNeedFix.equals(result)){
              msg += "部分修复成功。";
          }else{
              msg += "失败。";
          }
      }
      return msg;
  }
  /**
   * 将返回的内容格式化成JSON字符串
   * @param result
   * @param msg
   * @param retList
   * 如果需要传入workflowid和requestid，将数据放在map的list里面传进来,输出信息放在resultstr里面
   * @return
   */
  
  public JSONObject formatReturnJson(String result,String msg,List retList){
      return formatReturnJson(result, msg, retList,null);
  }
  public JSONObject formatReturnJson(String result,String msg,List retList,CheckBase checkBase){
      JSONObject jsonObj = new JSONObject();
      JSONArray jsonList = new JSONArray();
      try {
        if(result == "") result = resultOk;
        jsonObj.put("result", result);
        jsonObj.put("msg", msg);
        if(checkBase != null ){
            jsonObj.put("classname", checkBase.getClass().getName());
            jsonObj.put("classcontent", checkBase.getClassName());
        }
        if("1".equals(needReload)){
            jsonObj.put("needReload", "1");
            needReload = "";
        }
        if(retList != null){
            for(int i = 0 ; i < retList.size(); i++){
                String retStr = "";
                Map tempMap = null;
                try{
                    retStr = (String)retList.get(i);
                }catch(Exception e){
                    tempMap = (Map)retList.get(i);
                }
                //判断是否是map
                JSONObject jsonObjtemp = new JSONObject();
                if(tempMap != null){
                    if(checkBase != null ){
                        tempMap.put("classname", checkBase.getClass().getName());
                    }
                    //Map tempMap = transStringToMap(retStr);
                    //如果设定了链接地址，没有设定链接显示名字，默认为"设置地址"
                    if(tempMap.get("linkurl") != null && !"".equals(tempMap.get("linkurl")) && (tempMap.get("linkname") == null || "".equals(tempMap.get("linkname")))){
                        tempMap.put("linkname","设置地址");
                    }
                    java.util.Map.Entry entry;
                    for(Iterator iterator = tempMap.entrySet().iterator(); iterator.hasNext();)
                    {
                      entry = (java.util.Map.Entry)iterator.next();
                      jsonObjtemp.put(entry.getKey().toString(), null==entry.getValue()?"":entry.getValue().toString());
                    }
                }else{
                    jsonObjtemp.put("showMessage", retStr);
                }
                jsonList.put(jsonObjtemp);
            }
        }
        jsonObj.put("retList", jsonList);
    } catch (JSONException e) {
        e.printStackTrace();
    }
      return jsonObj;
  }
  /**
   * 方法名称:transStringToMap
   * 传入参数:mapString 形如 username=chenziwen,password=1234
   * 返回值:Map
  */
  public static Map transStringToMap(String mapString){
    Map map = new HashMap();
    java.util.StringTokenizer items;
    for(StringTokenizer entrys = new StringTokenizer(mapString, ",");entrys.hasMoreTokens(); 
      map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
        items = new StringTokenizer(entrys.nextToken(), "=");
    return map;
  }
  /**
   * 方法名称:transMapToString
   * 传入参数:map
   * 返回值:String 形如 username=chenziwen,password=1234
  */
  public static String transMapToString(Map map){
    java.util.Map.Entry entry;
    StringBuffer sb = new StringBuffer();
    for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)
    {
      entry = (java.util.Map.Entry)iterator.next();
        sb.append(entry.getKey().toString()).append( "=" ).append(null==entry.getValue()?"":
        entry.getValue().toString()).append (iterator.hasNext() ? "," : "");
    }
    return sb.toString();
  }

  public static String null2String(String s) {
      return s == null ? "" : s;

  }

  public static int getIntValue(String v) {
      return getIntValue(v, -1);
  }
  public static int getIntValue(String v, int def) {
      try {
          return Integer.parseInt(v);
      } catch (Exception ex) {
          return -1;
      }
  }


}